// 引用百度地图微信小程序JSAPI模块   
var sign_flag;
var bmap = require('../../libs/bmap-wx/bmap-wx.min.js');
var app = getApp();
var util = require("../../utils/util.js");

// pages/home/home.js 
Page({
  /**
   * 页面的初始数据
   */
  data: {
    popup: false, //是否赞一键获取手机号码
    signpopup: true, //签到模态框
    signstate: 1,
    phone: '', //手机号码
    ak: "wlXIw8P8X0mKSgpQ4IpCS7Z2QBx3YiSE", //请求百度api的ak码
    weatherData: '', //当前位置的天气数据
    futureWeather: [], //未来几天的天气情况 
    listH: '', //盒子高度
    temperature: '', //当前温度
    title_data: '', //最近设备信息
    getCardList: [], //获取我的卡信息

    // 签到
    is_login: false,
    integral_conf:{},//积分赠送
    sign_day: {},
    signstate: '',
    toDay:'',//今天

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.getStatusMsg(); //获取就近设备
    wx.setStorageSync('inviter_id', 0);
    if (options && util.isExitsVariable(options.q)) {
      var parm = decodeURIComponent(options.q); //字符分割 console.log(scan_url); //打印出url//分割网址，提取出参数
      var parm_arr = parm.split("inviter_id=");
      var inviter_id = parm_arr[1];
      wx.setStorageSync('inviter_id', inviter_id);
    }
      //二维码进入获取参数
     if (util.isExitsVariable(options.scene) && options.scene) {
        var scene = util.sceneToArr(decodeURIComponent(options.scene));
        console.log(scene, "scne", scene.pid)
        if (util.isExitsVariable(scene.pid)) {
          wx.setStorageSync('inviter_id', scene.pid);
        }

      }
    

    //app.getToken();
    //获取百度天气
    var BMap = new bmap.BMapWX({
      ak: that.data.ak
    });
    var fail = function (data) {

    };
    var success = function (data) {
      var weatherData = data.currentWeather[0];
      //切取实时温度
      var cuting = data.currentWeather[0].date.substring(14);
      var cutEnd = cuting.substring(-1, 3);
      var cutlast = cutEnd.split("℃");

      var futureWeather = data.originalData.results[0].weather_data; //获取未来几天天气
      that.setData({
        weatherData: weatherData,
        futureWeather: futureWeather,
        temperature: cutlast[0],
      });
    }
    // 发起 百度天气weather请求   
    BMap.weather({
      fail: fail,
      success: success
    });



    //获取 当前位置的经纬度位置
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        var latitude = res.latitude;
        var longitude = res.longitude;
        var speed = res.speed;
        var accuracy = res.accuracy;

        wx.setStorageSync('lat', latitude);
        wx.setStorageSync('lng', longitude);
      }
    });


    //创建节点选择器
    var query = wx.createSelectorQuery();
    var getH = '';
    //获取当前屏幕高度
    wx.getSystemInfo({
      success: function (res) {
        getH = res.windowHeight;
      }
    });

    //选择id
    query.select('#getHightIs').boundingClientRect()
    query.exec(function (res) {
      var abc = Number(getH) - Number(res[0].height) - 45;
      that.setData({
        listH: abc
      })
    });


  },
  //跳转签到
  signState: function () {
    var that = this;
    var is_login = wx.getStorageSync('is_login');
    if (!is_login) {
      that.gologin();
      return
    } else {
      wx.navigateTo({
        url: '../sign/sign',
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    var openid = wx.getStorageSync('openid');
    var is_login = wx.getStorageSync('is_login') == true ? true : false;
    that.setData({
      is_login: is_login
    })
    // console.log(123, is_login)

    if (is_login) {
      that.getWaterCard(); //获取我的水卡信息
      this.getsign();//获取签到配置
      this.signDay();//签到天数
      this.getUser();
    } else {
      // that.getWaterCard();//获取我的水卡信息
    }
    that.getNewFun(6);
  },
  //text用户信息
  getNewFun(x = 5, y) {
    y = y || 'yellow'
    var a = [];
    for (let i = 0; i < 10; i++) {
      a[i] = function () {
        // console.log('i>>>', i);
      };
    }
    a[6]();
  },
  testShow() {
    var that = this;
    console.log('testShow');
    that.onShow();
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  //获取换芯记录
  getchangeRecord: function () {
    var that = this;
    app.ajax({
      url: 'Common/Common/getProvince',
      data: {},
      method: 'POST',
      success: function (res) {

      }
    })
  },
  //根据经纬度 获取最近设备
  getStatusMsg: function () {
    //wx.showLoading()
    var that = this;
    // 获取经纬度
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        // wx.hideLoading();   
        var latitude = res.latitude;
        var longitude = res.longitude;
        wx.setStorageSync('lat', latitude);
        wx.setStorageSync('lng', longitude);
        if (latitude == '' || longitude == '') {

        }
        app.ajax({
          url: 'User/Equipment/getStatus',
          data: {
            longitude: longitude,
            latitude: latitude
          },
          method: 'POST',
          success: function (res) {
            if (res.data.code == 1000 && res.data.data != null) {

              that.setData({
                title_data: res.data.data
              })
            } else if (res.data.data == null) {

            }
          }
        })


      },
      fail: function () {
        // app.showToast('您已取消授权位置信息,无法查看附近设备信息', "none", 3000, function () {});
      }

    })

  },
  // 获取我的水卡
  getWaterCard: function () {
    var token = wx.getStorageSync('token');
    var that = this;
    app.ajax({
      url: 'User/WaterCard/waterCardList',
      method: "POST",
      data: {},
      success: function (res) {
        if (res.data.code == 1000) {
          that.setData({
            getCardList: res.data.data,
          })
          wx.setStorageSync('isgetCardList', res.data.data);
          that.getUser();
        } else {
          app.showToast(res.data.message, "none", 2000, function () {});
        }
      }
    })
  },
  /*水站监控 ***********************************************************/
  monitoring() {
    
    wx.navigateTo({
      url: '../monitoring/monitoring',
    })
  },
  //水质查询
  waterQuality() {

    wx.navigateTo({
      url: '../waterQuality/waterQuality',
    })
  },
  //健康话题
  healthTopic() {
    wx.navigateTo({
      url: '../healthTopic/healthTopic',
    })
  },
  //活动
  activity() {
    wx.navigateTo({
      url: '../activity/activity',
    })
  },
  //领券中心
  voucherCenter() {
    var that = this;
    var is_login = wx.getStorageSync('is_login');
    if (!is_login) {
      that.gologin();
      return
    } else {
      wx.navigateTo({
        url: '../vouchercenter/vouchercenter',
      })
    }
  },
  /***********************************************************/
  //跳转充值
  jumpType() {
    var that = this;
    var is_login = wx.getStorageSync('is_login');
    if (!is_login) {
      that.gologin();
      return
    } else {
      wx.navigateTo({
        url: '../cardRecharge/cardRecharge',
      })
    }
  },


  //扫码
  scan: function () {
    var that = this;
    var is_login = wx.getStorageSync('is_login');
    if (!is_login) {
      that.gologin();
      return
    } else {
      // 只允许从相机扫码
      wx.scanCode({
        onlyFromCamera: true,
        success: (res) => {
          console.log('success', res)
          var newsp = res.result.split("=");
          if (newsp.length == 2 && newsp[2] != '') {
            wx.navigateTo({
              url: '../gettingWater/gettingWater?equipment_sn=' + newsp[1] + '&have=' + 1,
            })
          } else {
            app.showToast('扫码失败请重试', "none", 2000, function () {});
          }
        },
        fail: (res) => {
          console.log('fail', res)
        }
      })
    }
  },
  //跳转水卡管理
  cardManage() {
    var that = this;
    var is_login = wx.getStorageSync('is_login');
    if (!is_login) {
      that.gologin();
      return
    } else {
      wx.navigateTo({
        url: '../cardManage/cardManage',
      })
    }
  },
  //积分抽奖
  lottery() {
    var that = this;
    var is_login = wx.getStorageSync('is_login');
    if (!is_login) {
      that.gologin();
      return
    } else {
      wx.navigateTo({
        url: '../lottery/lottery',
      })
    }
  },
  //获取用户信息
  getUser() {
    var that = this;
    app.ajax({
      url: "User/User/getUser",
      data: {},
      success: function (res) {
        if (res.data.code == 1000) {
          wx.setStorageSync('phone', res.data.data.phone);
          wx.setStorageSync('user_id', res.data.data.user_id)
          that.setData({
            phone: res.data.data.phone
          })
        } else {
          wx.setStorageSync('token', '');
          // app.getToken();
          that.setData({
            popup: true
          })
          //app.showModal('', res.data.message);return;
        }
      }
    })
  },
  // 关闭签到模态框
  signclose() {
    var that = this;
    that.setData({
      signpopup: false
    })
  },
  //取消一键登录
  abolish() {
    var that = this;
    that.setData({
      popup: false
    })
  },
  //获取用户手机号码
  getPhoneNumber: function (e) {
    var iv = e.detail.iv;
    var encryptedData = e.detail.encryptedData;
    var that = this;
    if (e.detail.errMsg == 'getPhoneNumber:fail:cancel to confirm login' || e.detail.errMsg == 'getPhoneNumber:fail user deny') {
      that.setData({
        popup: false
      }) //关闭弹窗
      wx.navigateTo({
        url: '../login/login',
      })
    } else {
      that.getAjaxPhone(iv, encryptedData); //后台解析手机信息
    }
  },
  //后台解析手机号码
  getAjaxPhone(iv, encryptedData) {
    var that = this;
    var session_key = wx.getStorageSync('session_key');
    app.ajax({
      url: "User/Wx/aesPhoneDecrypt",
      data: {
        key: session_key,
        iv: iv,
        data: encryptedData
      },
      success: function (res) {
        if (res.data.code == 1000) {
          that.setData({
            popup: false
          })
          wx.setStorageSync('phone', res.data.data.phoneNumber);
          wx.setStorageSync('token', ''); //清空本地token
          app.getToken(); //重新获取token 保存手机号码重新登录

        } else {
          app.showToast('用户信息解析失败请重新授权', "none", 2000, function () {});
          return;
        }
      }
    })
  },
  // 我的
  goCenter: function () {
    wx.redirectTo({
      url: '../person/person',
    })
  },
  //跳转
  invitation: function () {
    var that = this;
    var is_login = wx.getStorageSync('is_login');
    if (!is_login) {
      that.gologin();
      return
    } else {
      // wx.navigateTo({
      //   url: '../invitation/invitation',
      // })
    }
  },
  //需要前去登陆
  gologin() {
    wx.showModal({
      title: '该功能需要登录之后才能体验',
      content: '是否前去登录?',
      confirmColor:'#4EB7FF',	
      cancelColor: '#C4C4C4',
      success(res) {
        if (res.confirm) {
          wx.navigateTo({
            url: '../loginChoose/loginChoose',
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  bindgetuserinfofun: function (e) {
    var that = this;
    if (e.detail.errMsg == 'getUserInfo:fail:cancel to confirm login' || e.detail.errMsg == 'getUserInfo:fail auth deny') {
      app.showToast("取消登录", "none", 2000, function () {});
    } else {
      that.setData({
        userInfo: e.detail.userInfo
      })
      console.log('获取到的授权信息', that.data.userInfo);
      that.editUserInfo(that.data.userInfo); //更新一次用户信息
      wx.setStorageSync('avatarUrl', e.detail.userInfo.avatarUrl); //缓存头像
      wx.setStorageSync('nickName', e.detail.userInfo.nickName); //缓存名称
    }
  },
  //修改用户信息
  editUserInfo(userMsg) {
    var that = this;
    app.ajax({
      url: "User/User/editUserInfo",
      data: {
        avatar_img: userMsg.avatarUrl,
        username: userMsg.nickName,
      },
      success: function (res) {
        if (res.data.code == 1000) {

        } else {

        }
        wx.navigateTo({
          url: '../invitation/invitation',
        })
      }
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    this.shareLogFun(1); //记录
    var user_id = wx.getStorageSync('user_id');
    var pro = wx.getStorageSync('promoter') || 1;
    var cha = wx.getStorageSync('channel') || 1;
    return {
      title: '我发现了一个好用的生活小工具，快来加入哟~',
      imageUrl: 'https://qiniu.51204433.com/297b58717e759b9df6a812c0def8a4f0.png', //'../../images/yh_bg.png',
      path: 'pages/home/home?pid=' + user_id + "&way=1&pro=" + pro + "&cha=" + cha,
      success: function (res) {
        // 转发成功
        app.showToast('转发成功')
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  //分享记录
  shareLogFun(s_way) {
    var that = this;
    app.ajax({
      url: 'User/Share/shareLog',
      method: "POST",
      data: {
        type: 1,
        share_way: s_way
      }, //1是邀请好友 2分享详情 
      success: function (res) {
        if (res.data.code = 1000) {

        } else {

        }
      }

    })
  },
  //去充值
  toTopup: function () {
    //console.log(e.currentTarget.dataset.cardid)

    var that = this;
    var is_login = wx.getStorageSync('is_login');
    if (!is_login) {
      that.gologin();
      return
    } else {
      wx.navigateTo({
        url: "../topUp/topUp?card=" + '',
      })
    }
  },
  
  //签到
    //获取签到配置
    getsign: function () {
      var that = this;2
      app.ajax({
        url: 'User/Sign/integral_conf',
        data: {},
        method: 'POST',
        success: function (res) {
          if (res.data.code == 1000) {
            var integral_conf=res.data.data;
            integral_conf.seven = parseInt(integral_conf.seven) + parseInt(integral_conf.sign);
            integral_conf.three = parseInt(integral_conf.three) + parseInt(integral_conf.sign);
            that.setData({
              integral_conf
            })
          }
        }
      })
    },
    //获取签到天数
    signDay: function () {
      var that = this;

      app.ajax({
        url: 'User/Sign/sign_day',
        data: {},
        method: 'POST',
        success: function (res) {
          console.log(res);
          if (res.data.code == 1000) {
            if (res.data.data.is_sign == 1) {
              sign_flag = false
            } else {
              sign_flag = true
            }
            var sign_day = res.data.data
            // sign_day.is_sign=0;//模拟数据
            // sign_day.cycle_day=3;//模拟数据
            // console.log('签到数据', sign_day)
            that.setData({
              sign_day,
              signstate: res.data.data.is_sign,//0今天未签到 1已签到 
            })
          }
        }
      })
    },
  
    signOver() { this.data.signstate==1?app.showToast('今日已签到,明天再来吧'):''},
    //签到
    signfun: function (e) {
      var current = e.currentTarget.dataset.current;
      var that = this;
      if (!sign_flag) {
        app.showToast('今日已签到');
        return false;
      }
      app.ajax({
        url: 'User/Sign/sign',
        data: {},
        method: 'POST',
        success: function (res) {  
          if (res.data.code == 1000) {
            var integral_conf = that.data.integral_conf;
            integral_conf.sign_data.forEach((item,index)=>{
              if (item.current_cycle_day == current){
                integral_conf.sign_data[index].is_sign = true;
              }
            })
            // integral_conf.sign_data[index].is_sign=true;
            // console.log('>>>>>', integral_conf)
            that.setData({
              signstate: 1,
              integral_conf
            });
            sign_flag = false
          } else {
            // sign_flag = false
          }
          // app.showToast(res.data.message);
          that.signDay();//获取签到状态
        }
      })
    },
  
})